using System;
using System.BusinessObjects.Transactions;
using Blazing.BusinessObjects.Tagging;
using NHibernate;
using NHibernate.Criterion;

namespace Blazing.BusinessObjects.Queries
{
    public class QrySearchTaxonomyTagsByTag
    {
        public static IQuery Query(int tagId)
        {
            string nql = "select t from Taxonomy t where t in (select tt.Taxonomy.ID from TaxonomyTag tt where tt.Tag.ID=:tagId)";
            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(nql);
            qry.SetInt32("tagId", tagId);

            qry.SetCacheable(true);
            return qry;
        }

        /// <summary>
        /// Returns a taxonomy tag from a specific tag name
        /// </summary>
        public static IQuery Query(int taxonomyId, string tagname)
        {
            string hql = "select tt from TaxonomyTag tt join tt.Tag t where t.Name=:tagName and tt.Taxonomy.ID=:taxonomyId";
            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(hql);
            qry.SetString("tagName", tagname);
            qry.SetInt32("taxonomyId", taxonomyId);

            qry.SetCacheable(true);
            return qry;
        }

        /// <summary>
        /// Returns a taxonomy tag from a specific tag name
        /// </summary>
        public static IQuery Query(int taxonomyId, int tagId)
        {
            string hql = "select tt from TaxonomyTag tt where tt.Tag.ID=:tagId and tt.Taxonomy.ID=:taxonomyId";
            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(hql);
            qry.SetInt32("tagId", tagId);
            qry.SetInt32("taxonomyId", taxonomyId);

            qry.SetCacheable(true);
            return qry;
        }

        public static IQuery Query(bool attachedOnly)
        {
            string hql;
            IQuery qry;          
            if (attachedOnly)
            {
                hql = "select distinct t from Building b join b.BuildingTaxonomyTags t order by t.Tag.Name";                
            }
            else
            {
                hql = "select tt from TaxonomyTag tt order by tt.Tag.Name";                
            }            
            qry = UnitOfWork.CurrentSession.CreateQuery(hql);
            qry.SetCacheable(true);
            return qry;
        }
    }
}
